package com.xsoft.sms.cmpp20.message.impl;

import com.xsoft.sms.cmpp20.message.ICMPP20Message;
import com.xsoft.sms.cmpp20.message.exception.CMPP20MessaageException;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * package: {PACKAGE_NAME}
 * User: zhanglm
 * Date: 12-9-21
 * Time: 下午12:21
 * Description:
 */
public class CMPP20MessageConnectReqBody implements ICMPP20Message {


	@Override
	public byte[] toBuffer() {
		ByteBuffer buffer = ByteBuffer.allocate(CMPP20MessageConnectReq.BODY_LENGTH);
		buffer.put(spId.getBytes());
		buffer.put(getAuthenticatorSource());
		buffer.put(version);
		buffer.putInt(Integer.valueOf(timestamp));
		return buffer.array();
	}

	@Override
	public void fromBuffer(byte[] buffer) throws CMPP20MessaageException {
		throw new UnsupportedOperationException();
	}

	public String getSpId() {
		return spId;
	}

	public void setSpId(String spId) {
		this.spId = spId;
	}

	public byte getVersion() {
		return version;
	}

	public void setVersion(byte version) {
		this.version = version;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private byte[] getAuthenticatorSource() {
		byte [] b09 = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00};
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			return new byte[0];
		}
		md5.update(spId.getBytes());
		md5.update(b09);
		md5.update(password.getBytes());
		md5.update(timestamp.getBytes());
		return md5.digest();
	}


	private String spId;
	private byte   version;
	private String timestamp;
	private String password;
}
